package com.fenghongzhang.day018;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.menu.MenuWrapperICS;

import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;



public class MainActivity extends AppCompatActivity {

    private MediaPlayer mediaPlayer = new MediaPlayer();
    private ListView lv;
    private Button pause;
    private Button restart;
    private Button nav;
    private int index = 0;
    private Button next;
    private SeekBar seekBar;

    private boolean isNext;

    private Button model;

    private int playModel = 1; //播放模式

    private Timer timer;
    private List<Song> songList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        /**
         * 最大值
         * 当前进度值
         */
        seekBar = (SeekBar) findViewById(R.id.seek_bar);

        model = (Button) findViewById(R.id.model);


        lv = (ListView) findViewById(R.id.lv);
        pause = (Button) findViewById(R.id.pause);
        restart = (Button) findViewById(R.id.restart);
        nav = (Button) findViewById(R.id.nav);
        next = (Button) findViewById(R.id.next);

        //动态请求权限
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){//6.0
           requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},100);
        }

        //应该从sd中读取文件来填充
        //List<Song> list = new ArrayList<>();

        //从sd中读取数据到list中

        //文件一直没有. 为空

        //list.add(new Song("歌名","歌手","时长","1","2","3"));


        //点击以后,开始播放
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                index = position;
                play(position);
            }
        });

        //拖动进度条的监听器
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });


    }

    //提取播放的方法
    private void play(int position) {

        //取消定时器
        if(timer != null){
            timer.cancel();
        }

        //每次播放之前,重置mp
        mediaPlayer.reset();
        //数据源
        try {
            final Song song = songList.get(position);
            //  /storage/emulated/0/Music/Jam - 七月上.mp3
            mediaPlayer.setDataSource(song.getData());
            //异步加载
            mediaPlayer.prepareAsync();
            //监听器加载完毕
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {

                    //进度条
                    seekBar.setMax(Integer.parseInt(song.getDuration()));

                    //更新进度值
                    timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            seekBar.setProgress(mediaPlayer.getCurrentPosition());
                        }
                    },0,1000);
                    //开始播放
                    mediaPlayer.start();
                }
            });

            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    playModel();
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void playModel() {
        // 才要判断是随机还是下一首,还是单曲
        if(playModel == MusicUtil.RANDOM){
            index = new Random().nextInt(songList.size());
        }else if(playModel == MusicUtil.ORDER){

            if(isNext){
                //播放下一首的逻辑
                if (++index > songList.size()-1){  //6 > 5
                    index = 0;
                }
            }else{
                //播放上一首
                if(--index < 0 ){
                    index = 0;
                }
            }


        }else if (playModel == MusicUtil.SINGLE){
        }
        play(index);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 100 && grantResults[0]== PackageManager.PERMISSION_GRANTED){

            //读取sd卡的内容.
             songList = MusicUtil.getMusic(this);

            MyAdapter myAdapter = new MyAdapter(this,songList);
            lv.setAdapter(myAdapter);


        }else{
            finish();
        }
    }

    //暂停
    public void pause(View view) {
        mediaPlayer.pause();
    }

    //继续播放
    public void restart(View view) {
        mediaPlayer.start();
    }

    //点击事件下一首
    public void next(View view) {
        isNext = true;
        playModel();
    }


    //上一首
    public void pre(View view) {
        isNext = false;
        playModel();
    }




    //更改播放模式
    public void model(View view) {
        final PopupWindow popupWindow = new PopupWindow(this);

        View inflate = LayoutInflater.from(this).inflate(R.layout.pop_layout,null);

        //3要素
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setContentView(inflate);

        //布局中的点击事件
        TextView order = inflate.findViewById(R.id.pop_order);
        order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playModel = MusicUtil.ORDER;
                popupWindow.dismiss();
            }
        });

        TextView random = inflate.findViewById(R.id.pop_random);
        random.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playModel = MusicUtil.RANDOM;
                popupWindow.dismiss();
            }
        });

        TextView single = inflate.findViewById(R.id.pop_single);
        single.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playModel = MusicUtil.SINGLE;
                popupWindow.dismiss();
            }
        });


        //点击外部课取消
        popupWindow.setOutsideTouchable(true);

        popupWindow.showAsDropDown(model,0,-350);

    }
}
